package com.gp.pj.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.gp.pj.entity.Dict;
import com.gp.pj.entity.DictItem;
import com.gp.pj.service.DictItemService;
import com.gp.pj.service.DictService;
import com.gp.pj.utils.ResultUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Chloe
 * @since 2020-12-14
 */
@RestController
@RequestMapping("/")
public class DictController {

    @Resource
    DictService dictService;

    @Resource
    DictItemService dictItemService;

    @ResponseBody
    @GetMapping( value = "/getDictList")
    public ResultUtils dictList() {
        return dictService.getDictList();
    }

    @ResponseBody
    @PostMapping( value = "saveDict")
    public ResultUtils saveDict(@RequestBody JSONObject jsonRe){
        Dict dict = jsonRe.toJavaObject(Dict.class);
        boolean save = dictService.save(dict);
        if (save) {
            return ResultUtils.success();
        } else {
            return ResultUtils.failure("新增字典信息失败");
        }
    }

    @ResponseBody
    @PostMapping( value = "updateDict")
    public ResultUtils updateDict(@RequestBody JSONObject jsonRe){
        Dict dict = jsonRe.toJavaObject(Dict.class);
        boolean update = dictService.updateById(dict);
        if (update) {
            return ResultUtils.success();
        } else {
            return ResultUtils.failure("更新字典信息失败");
        }
    }

    @ResponseBody
    @PostMapping( value = "deleteDict")
    public ResultUtils deleteDict(@RequestBody JSONObject jsonRe){
        Dict dict = jsonRe.toJavaObject(Dict.class);
        boolean removeItem = dictItemService.remove(Wrappers.<DictItem>lambdaQuery().eq(DictItem::getDictId, dict.getId()));
        if (removeItem) {
            boolean remove = dictService.removeById(dict);
            if (remove) {
                return ResultUtils.success();
            } else {
                return ResultUtils.failure("删除字典信息失败");
            }
        } else {
            return ResultUtils.failure("删除字典信息失败");
        }
    }

}
